package com.example.axis2.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.axis2.transport.http.AxisServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

@Configuration
@Slf4j
public class WebserviceConfig {

    //服务访问前缀
    public static final String URL_PATH = "/services/*";
    //axis2配置文件的根路径
    public static final String SERVICES_ROOT_DIRECTORY = "WEB-INF";
    //services.xml文件的位置
    public static final String SERVICES_FILE_PATH = SERVICES_ROOT_DIRECTORY + "/services/axis2/META-INF/services.xml";
    //AXIS2参数key
    public static final String AXIS2_REP_PATH = "axis2.repository.path";

    /**
     * 注册 Axis 的Servlet，指定 url-mapping 为 /services
     *
     * @return ServletRegistrationBean
     */
    @Bean
    public ServletRegistrationBean<AxisServlet> axis2Servlet() throws IOException {
        ServletRegistrationBean<AxisServlet> servletRegistrationBean = new ServletRegistrationBean<>();
        servletRegistrationBean.setServlet(new AxisServlet());
        servletRegistrationBean.addUrlMappings(URL_PATH);

        // 通过默认路径无法找到services.xml，这里需要指定一下路径，且必须是绝对路径
        String rootDir = this.getClass().getClassLoader().getResource(SERVICES_ROOT_DIRECTORY).getPath();

        // 如果是jar包，同样无法找到 services.xml
        // 暂时采取的办法是：把 services.xml 连同根路径一起复制到 jar 包的外面
        if (rootDir.toLowerCase().startsWith("file:")) {
            File file = new File(SERVICES_FILE_PATH);
            File parentFile = file.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            InputStream is = this.getClass().getClassLoader().getResourceAsStream(SERVICES_FILE_PATH);
            Files.copy(is, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
            is.close();
            rootDir = new File(SERVICES_ROOT_DIRECTORY).getAbsolutePath();
        }
        log.info("{} ======>> {}", AXIS2_REP_PATH, rootDir);
        servletRegistrationBean.addInitParameter(AXIS2_REP_PATH, rootDir);
        servletRegistrationBean.setLoadOnStartup(1);
        return servletRegistrationBean;
    }
}
